package com.qf.java2102.qihaonan.hotel.service.impl;

import com.qf.java2102.qihaonan.hotel.constant.MessageConstant;
import com.qf.java2102.qihaonan.hotel.dao.IFoodDao;
import com.qf.java2102.qihaonan.hotel.dao.IFoodTypeDao;
import com.qf.java2102.qihaonan.hotel.dao.impl.FoodDaoImpl;
import com.qf.java2102.qihaonan.hotel.dao.impl.FoodTypeDaoImpl;
import com.qf.java2102.qihaonan.hotel.entity.PageBean;
import com.qf.java2102.qihaonan.hotel.entity.ResultVO;
import com.qf.java2102.qihaonan.hotel.pojo.Food;
import com.qf.java2102.qihaonan.hotel.service.IFrontService;
import com.qf.java2102.qihaonan.hotel.utils.JdbcUtils;

import java.util.List;

/**
 * @author qhn
 * @version 1.0
 */
public class FrontServiceImpl implements IFrontService {

    private IFoodTypeDao foodTypeDao = new FoodTypeDaoImpl();
    private IFoodDao foodDao = new FoodDaoImpl();


    @Override
    public ResultVO<PageBean> pageBean(Integer currentPage, String foodName, Long typeId) {

        try {
            JdbcUtils.begin();

            //菜品分页数据
            PageBean<Food> pageBean = new PageBean<>();
            //前台点击的
            pageBean.setCurrentPage(currentPage);
            //处理菜品名称
            foodName = foodName == null || "".equals(foodName.trim()) ? "" : "%" + foodName.trim() + "%";
            // null 或者 "   "    --> ""
            // " 鸡 "   --> "%鸡%"
            //SELECT * FROM t_food WHERE food_name LIKE '%鸡%' LIMIT 0,6
            //foodName = "" 或者 "%条件%"
            //typeId = 0 或者 真正的typeId值
            List<Food> foods = foodDao.findByCondition(foodName, typeId, currentPage, pageBean.getPageSize());
            //当前页集合数据
            pageBean.setList(foods);
            //select count(1) from t_food
            Long count = foodDao.countByCondition(foodName, typeId);
            //总数
            pageBean.setTotalCounts(count);
            //总条数
            pageBean.setTotalPages();

            JdbcUtils.commit();
            return ResultVO.ok(MessageConstant.FOOD_PAGE_SUCCESS, pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtils.rollback();
        } finally {
            JdbcUtils.release(JdbcUtils.getConnection());
        }
        return ResultVO.error(MessageConstant.COMMON_ERROR);
    }


}
